package com.hyj.ecp.backstage.goods.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import com.ecp.ResultObject;
import com.ecp.goods.GoodsQO;
import com.ecp.goods.GoodsTrait;
import com.ecp.goods.GoodsTypeQO;
import com.hyj.ecp.backstage.goods.service.IBackGoodsService;
import com.hyj.ecp.common.constant.SysConstant;
import com.hyj.ecp.common.dao.IjdbcDAO;
@Service
public class BackGoodsService implements IBackGoodsService {

	Log logger = LogFactory.getLog(BackGoodsService.class);
	
	@Resource(name="jdbcDao")
    private  IjdbcDAO dao;

	@Override
	public Map<String,Object> queryGoodsType(GoodsTypeQO qo) {
		List<Object> param = new ArrayList<Object>();
		String sql = "  select t.id,t.name,t.logo,t.desc," +
				"DATE_FORMAT( t.createtime,'%Y-%m-%d %H:%i:%s') AS createtime  ," +
				"t.createperson," +
				" DATE_FORMAT( t.modifytime,'%Y-%m-%d %H:%i:%s') AS modifytime," +
				" t.modifyperson," +
				"IFNULL((select g.`NAME` FROM t_goods_type g where g.ID=t.PID),'顶级分类') as pid  "+
		"   FROM  t_goods_type AS t where 1 = 1";
		if(qo.getName()!=null&&qo.getName().length()>0){
			sql= sql+" and t.name like ? ";
			param.add("%"+qo.getName()+"%");
		}
		
		if(qo.getPid()!=null&&qo.getPid().length()>0){
			sql= sql+" and t.pid = ? ";
			param.add(qo.getPid());
		}
		
		if(qo.getId()!=null&&qo.getId().length()>0){
			sql= sql+" and t.id = ? ";
			param.add(qo.getId());
		}
		
		/*int a = dao.queryCount(sql, param.toArray());
		//List<ClientUserQO> list= dao.queryForList(sql, qo.getCurPage(), qo.getSize(),  new Object[]{},ClientUserQO.class);
		List<Map<String,Object>> list= dao.queryForList(sql, qo.getCurPage(), qo.getSize(),  param.toArray()); */
		ResultObject result = dao.pageQuery(sql, qo.getCurPage(), qo.getSize(),  param.toArray());
		Map<String,Object> vo = new HashMap<String,Object>();
    	vo.put("rowTotal", result.getRowCount());
    	vo.put("infoContent", result.getRows());
		return  vo;

	}
	
	@Override
	public int saveGoodsType(GoodsTypeQO qo) {
		String sql = "   INSERT INTO  `t_goods_type` (  `NAME`, `LOGO`,`DESC`,`CREATETIME`,`CREATEPERSON`,  `PID`)" +
				    "   VALUES (?,?,?,NOW(),?,?)"; 
		
		return dao.update(sql, new Object[]{qo.getName(),qo.getLogo(),qo.getDesc(),qo.getOptUser(),qo.getPid()});
	}
	
	@Override
	public int deleteGoodsType(GoodsTypeQO qo) {
		String sql= "  SELECT COUNT(1) FROM  t_goods t WHERE t.TYPEID = ?   ";
		//先判断这个分类下面有没有商品，如果有就不能删除
		Integer num = dao.queryForInt(sql, new Object[]{qo.getId()});
		if(num>0){
			return -1;
		}
	   sql = " DELETE FROM t_goods_type  WHERE   id= ?   "; 
       return dao.update(sql, new Object[]{qo.getId()});
	}
	
	@Override
	public int updateGoodsType(GoodsTypeQO qo) {
		String sql = "  UPDATE `t_goods_type` SET   " +
				" `NAME` = ?, `LOGO` = ?, `DESC` = ?, `MODIFYTIME` = NOW(), `MODIFYPERSON` = ?, `PID` = ? " +
				"  WHERE `ID` = ? "; 
		   logger.info(qo.getId()+"商品类别更新："+sql);
           return dao.update(sql, new Object[]{qo.getName(),qo.getLogo(),qo.getDesc(),qo.getOptUser(),qo.getPid(),qo.getId()});
	}

	@Override
	public Map<String,Object> queryGoods(GoodsQO qo){
		List<Object> param = new ArrayList<Object>();
		StringBuffer sql = new StringBuffer();
		  sql.append( " select   `id`,(SELECT t1.NAME FROM t_goods_type t1 WHERE t1.id=t.TYPEID) AS typeid ,  `name`,  `logo`, `vipprice`,  `price`, `mprice`," +
				" DATE_FORMAT( t.ADDTIME,'%Y-%m-%d %H:%i:%s') AS addtime  , " +
				"`addperson`, " +
				" DATE_FORMAT( modifytime,'%Y-%m-%d %H:%i:%s') AS modifytime  ,  " +
				"`modifyperson`, `title`, `desc` " +
				"from  `t_goods` t where 1=1 ");
		if(qo.getName()!=null&&qo.getName().length()>0){
			sql.append(" and t.name like ? ");
			param.add("%"+qo.getName()+"%");
		}
		
		if(qo.getTypeId()!=SysConstant.NULL_ID){
			sql.append(" and t.typeid=? ");
			param.add(qo.getTypeId());
		}
		
		if(qo.getId()!= SysConstant.NULL_ID){
			sql.append(" and t.id = ? ");
			param.add(qo.getId());
		}
		
		if(qo.getIsHot()!=null&& !"".equals(qo.getIsHot())){
			sql.append(" and t.isHot = ? ");
			param.add(qo.getIsHot());
		}
		
		if(qo.getIsAd()!=null&& !"".equals(qo.getIsAd())){
			sql.append(" and t.isAd = ? ");
			param.add(qo.getIsAd());
		}
		
		if(qo.getExtAttr()!=null&& "1".equals(qo.getExtAttr())){
			sql.append(" AND EXISTS (  SELECT 1 FROM t_goods_attr a WHERE a.goodsid = t.ID  )  ");
		}
		
		if(qo.getExtAttr()!=null&& "0".equals(qo.getExtAttr())){
			sql.append(" AND ! EXISTS (  SELECT 1 FROM t_goods_attr a WHERE a.goodsid = t.ID  )  ");
		}
		sql.append(" order by t.id desc ");
		try {
			logger.info("商品查询:"+sql.toString());
			ResultObject result = dao.pageQuery(sql.toString(),
					qo.getCurPage(), qo.getSize(), param.toArray());
			Map<String, Object> vo = new HashMap<String, Object>();
			vo.put("rowTotal", result.getRowCount());
			vo.put("infoContent", result.getRows());
			return vo;
		} catch (Exception e) {
			logger.error("", e);
			return null;
		}
	}

	@Override
	public int deleteGoods(GoodsQO qo) {
		String sql = " DELETE FROM t_goods  WHERE   id= ?   "; 
        return dao.update(sql, new Object[]{qo.getId()});
	}

	@Override
	public int saveGoods(GoodsQO qo) {
		String sql = "   INSERT INTO `t_goods` (  `TYPEID`, `NAME`, `LOGO`, `vipprice`, `PRICE`, " +
				"`MPRICE`, `ADDTIME`, `ADDPERSON`, `TITLE`,   `DESC` ,`ATTRIBUTE` ,`NUM`,`POINT`" +
				",`COLORS` ,`SIZES`  )" +
				"VALUES ( ?,?,?,?,?,?, NOW(), ?,?,?,?,?,?,?,?);"; 
		logger.info(" 新增商品： "+sql);
		if(qo.getImgs()!=null&&qo.getImgs().length>0){
		 qo.setLogo(qo.getImgs()[0]);
		}
        int a =  dao.update(sql, new Object[]{
        		qo.getTypeId(),qo.getName(),qo.getLogo(),
        		qo.getVipPrice(),qo.getPrice(),qo.getmPrice(),
        		qo.getOptUser(), qo.getTitle(),qo.getDesc(),qo.getAttribute() ,qo.getNum(),qo.getPoint(),
                qo.getColors(),qo.getSizes() });
        
        //插入产品图片
        int goodsId = dao.queryForInt("  SELECT  LAST_INSERT_ID() ", new Object[]{});
        
        if(qo.getImgs()!=null){
	      for(String img:qo.getImgs()){
	      sql  = "   INSERT INTO  `t_goods_img` "+
             "     (`goodsid`,   `img`, `addtime`,  `addperson` ) "+
             "   VALUES (    ?,   ?,  NOW(),   ?  )  ";
	      
	         dao.update(sql, new Object[]{goodsId,img,qo.getOptUser()});
	         
	      } 
        }
        
        return a;
        
	 }

	@Override
	public int updateGoods(GoodsQO qo) {
		String  sql =" UPDATE `t_goods` SET   `TYPEID` = ?,  `NAME` = ?, " +
				" `LOGO` = ?, `vipprice` = ?, `PRICE` = ?, `MPRICE` = ?, " +
				" `MODIFYTIME` = NOW(), " +
				" `MODIFYPERSON` = ?, `TITLE` = ?, `DESC` = ?, `ATTRIBUTE` = ? , `ISHOT`=? , `ISAD`  =? ," +
				" `NUM` = ? ,`POINT` =? ,`COLORS`=? ,`SIZES` =?,  `VSAILES` = ?,`POINTPRICE` = ? "+
				"  WHERE `ID` = ? ";
		 logger.info("  修改商品： "+sql);
		 if(qo.getImgs()!=null&&qo.getImgs().length>0){
			 qo.setLogo(qo.getImgs()[0]);
	      }
		 int a = dao.update(sql, new Object[]{
	        		qo.getTypeId(),qo.getName(),qo.getLogo(),
	        		qo.getVipPrice(),qo.getPrice(),qo.getmPrice(),
	        		qo.getOptUser(), qo.getTitle(),qo.getDesc(),qo.getAttribute(),qo.getIsHot(),qo.getIsAd(),
	        		qo.getNum(),qo.getPoint(),qo.getColors(),qo.getSizes(),qo.getVsale(),qo.getPointPrice(),qo.getId()
	        });
		 
		 // 修改商品图片
		 sql = " delete from t_goods_img where  goodsid = ? ";
		 dao.update(sql, new Object[]{qo.getId()});
		 
		 if(qo.getImgs()!=null){
			 for(String img:qo.getImgs()){
			      sql  = "   INSERT INTO  `t_goods_img` "+
		             "     (`goodsid`,   `img`, `addtime`,  `addperson` ) "+
		             "   VALUES (    ?,   ?,  NOW(),   ?  )  ";
			      
			         dao.update(sql, new Object[]{qo.getId(),img,qo.getOptUser()});
			         
			      } 
	        }
		 
		 return  a;
	}

	@Override
	public GoodsQO querySingleGoods(GoodsQO qo) {
		List<Object> param = new ArrayList<Object>();
		GoodsQO vo = null;
		
		StringBuffer sql = new StringBuffer();
		  sql.append( " select   `id`,(SELECT t1.NAME FROM t_goods_type t1 WHERE t1.id=t.TYPEID) AS typeName,t.typeid ,  `name`,  `logo`, `vipprice`,  `price`, `mprice`," +
				" DATE_FORMAT( t.ADDTIME,'%Y-%m-%d %H:%i:%s') AS addtime  , " +
				"`addperson`, " +
				" DATE_FORMAT( modifytime,'%Y-%m-%d %H:%i:%s') AS modifytime  ,  " +
				"`modifyperson`, `title`, `desc`, `attribute`,`ishot` , `isad`,IFNULL(`NUM`,0) as `NUM`, IFNULL(`POINT`,0) as `POINT`,`COLORS` ,`SIZES`" +
				" , VSAILES as `vsale` , IFNULL(`POINTPRICE`,0) as `pointPrice` "+
		        "from  `t_goods` t where 1=1 ");
		if(qo.getName()!=null&&qo.getName().length()>0){
			sql.append(" and t.name like ? ");
			param.add("%"+qo.getName()+"%");
		}
		
		if(qo.getTypeId()!=SysConstant.NULL_ID){
			sql.append(" and t.typeid=? ");
			param.add(qo.getTypeId());
		}
		
		if(qo.getId()!= SysConstant.NULL_ID){
			sql.append(" and t.id = ? ");
			param.add(qo.getId());
		}
		
		try {
			logger.info("商品查询:"+sql.toString());
			vo = dao.queryForObject(sql.toString(), param.toArray(), GoodsQO.class);
			return vo;
		} catch (Exception e) {
			logger.error("", e);
			return null;
		}
	}
	
	public List<Map<String,Object>> queryGoodsImg(GoodsTrait qo) {
		try{
            String sql = " SELECT  t.img,t.addperson,t.addtime  FROM  t_goods_img t WHERE t.goodsid = ? " ;
            return dao.queryForList(sql, new Object[]{qo.getGoodsId()});
		}catch(Exception e){
			logger.error("", e);
			return null;
		}
	}

	@Override
	public int updateGoodsTrait(List<GoodsTrait> qo) {
		
		String  sql ="   ";
		/* return dao.update(sql, new Object[]{ 
        });*/
        for(GoodsTrait vo : qo){
        	sql ="  SELECT COUNT(1) FROM  t_goods_attr t WHERE t.goodsid = ?";
        	int n = dao.queryForInt(sql, new Object[]{vo.getGoodsId()});
        	if(n<=0){
	        	sql = "  INSERT INTO `ecp`.`t_goods_attr` " +
	        			"(`num`,`point`,   `goodsid`, `colors`, `sizes`, `addtime`, `addperson` ) " +
	        			"VALUES ( ?, ?, ?, ?, ?, now(), ?) ";
	        	logger.info("  增加商品购买属性： "+sql);
	        	return dao.update(sql, new Object[]{vo.getNum(),vo.getPoint(),vo.getGoodsId(),vo.getColors(),vo.getSizes(),
	        			vo.getOptUser() });
        	}else{
            	sql = "  UPDATE  `t_goods_attr` SET `num` = ? ,`point`= ?,  " +
            			 " `colors` = ?, " +
            			 " `sizes` = ?, " +
            			 " `modifytime` = now(), " +
            			 " `modifyperson` = ? " +
            			 "  WHERE goodsid = ? ";
            	logger.info("  修改商品购买属性： "+sql);
            	return dao.update(sql, new Object[]{vo.getNum(),vo.getPoint(),vo.getColors(),vo.getSizes(),
            			vo.getOptUser(),vo.getGoodsId() });
        	}
        }
        return 0;
	}

	

	
	
	
}
